

import 'dart:io';
import 'package:dio/dio.dart';
import 'package:life_milestones/MS-global-url.dart';
import 'package:life_milestones/MS-request.dart';
class MSOSSPolicy{
  String accessKeyId;
  String dir;
  String signature;
  String policy;
  String host;
  String callback;
  MSOSSPolicy({required this.host,required this.accessKeyId,required this.dir,required this.policy,required this.signature,required this.callback});
  factory MSOSSPolicy.fromJson(Map<String,dynamic> map){
    return MSOSSPolicy(host: map["host"], accessKeyId: map["accessKeyId"], dir: map["dir"], policy: map["policy"], signature: map["signature"],callback: map["callback"]);
  }

}


Future<String?> uploadFile(File file)async{
  try{
    var response = await MSRequest().get(MSGlobalUrl.getOSSPolicy);
    if(response["code"] == 0 && response["data"] != null){
     var policy = MSOSSPolicy.fromJson(response["data"]);
     return await execute(file, policy);
    }else{
      return null;
    }
  }catch(e){
    return null;
  }
}

Future<String?> execute(File file,MSOSSPolicy policy)async{
  try{
    var data = await FormData.fromMap({
      "ossaccessKeyId":policy.accessKeyId,
      "policy":policy.policy,
      "signature":policy.signature,
      "key": "${policy.dir}${DateTime.now().millisecondsSinceEpoch}${file.path.split(".")[1]}",
      'callback': policy.callback,
      "file":await MultipartFile.fromFile(file.path, filename: file.path.split("/")[1])
    });
    var reponse = await Dio(BaseOptions(baseUrl: policy.host)).post("",data: data);
    if(reponse.statusCode == 200 && reponse.data["code"] == 0){
      return reponse.data["data"]["filename"];
    }
  }catch(e){
    return null;
  }

}